import json
from datetime import datetime

from django.http import JsonResponse

from lapi_app.models.environment_model.environment import Environment
from lapi_app.view.user_view.token_check import access_token


def get_environment(request):
    data = json.loads(request.body)
    if not access_token(data["user_id"]):
        return JsonResponse({
            "code": 1001,
            "message": "登录失效，请重新登录"
        })
    env_result = []
    if data["env_id"] == "":
        return JsonResponse({
            "code": 100,
            "message": "env_id不可为空",
        })
    elif Environment.objects.filter(id=data["env_id"]).count() == 0:
        return JsonResponse({
            "code": 100,
            "message": "env_id不存在",
        })
    else:
        envs = Environment.objects.filter(id=data["env_id"])
        for env in envs:
            env_dict = {
                "environment_name": env.e_name,
                "environment_address": env.e_address,
                "environment_describe": env.e_describe,
            }
            env_result.append(env_dict)
        return JsonResponse({
            "code": 200,
            "message": "获取环境信息成功",
            "content": env_result
        })


def add_environment(request):
    data = json.loads(request.body)
    if not access_token(data["user_id"]):
        return JsonResponse({
            "code": 1001,
            "message": "登录失效，请重新登录"
        })
    try:
        if data["environment_name"] == "" or data["environment_address"] == "":
            return JsonResponse({
                "code": 100,
                "message": "环境名称或环境地址不可为空",
            })
        elif Environment.objects.filter(e_name=data["environment_name"]).exists():
            return JsonResponse({
                "code": 100,
                "message": "环境名称已存在，请重新输入",
            })
        else:
            try:
                Environment.objects.create(e_name=data["environment_name"], e_address=data["environment_address"],
                                           e_describe=data["environment_describe"], e_user_id=data["user_id"])
                return JsonResponse({
                    "code": 200,
                    "message": "新增环境成功"
                })
            except Exception as e:
                return JsonResponse({
                    "code": 100,
                    "message": "新增环境失败",
                    "Exception": str(e)
                })
    except Exception as e:
        return JsonResponse({
            "code": 100,
            "message": "新增环境失败",
            "Exception": str(e)
        })


def edit_environment(request):
    data = json.loads(request.body)
    if not access_token(data["user_id"]):
        return JsonResponse({
            "code": 1001,
            "message": "登录失效，请重新登录"
        })
    try:
        env_names = Environment.objects.exclude(id=data["env_id"])
        for t in env_names:
            if t.e_name == data["environment_name"]:
                return JsonResponse({
                    "code": 100,
                    "message": "环境名称已存在，请重新输入"
                })
        if data["environment_name"] == "" or data["environment_address"] == "":
            return JsonResponse({
                "code": 100,
                "message": "环境名称或环境地址不可为空",
            })
        else:
            try:
                Environment.objects.filter(id=data["env_id"]).update(e_name=data["environment_name"],
                                                                     e_address=data["environment_address"],
                                                                     e_describe=data["environment_describe"],
                                                                     e_user_id=data["user_id"],
                                                                     update_time=datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
                return JsonResponse({
                    "code": 200,
                    "message": "编辑环境成功"
                })
            except Exception as e:
                return JsonResponse({
                    "code": 100,
                    "message": "编辑环境失败",
                    "Exception": str(e)
                })
    except Exception as e:
        return JsonResponse({
            "code": 100,
            "message": "编辑环境失败",
            "Exception": str(e)
        })


def del_env(request):
    try:
        data = json.loads(request.body)
        if not access_token(data["user_id"]):
            return JsonResponse({
                "code": 1001,
                "message": "登录失效，请重新登录"
            })
        if data["env_id"] is None:
            return JsonResponse({
                "code": 100,
                "message": "id不能为空",
            })
        else:
            Environment.objects.filter(id=data["env_id"]).delete()
            return JsonResponse({
                "code": 200,
                "message": "删除成功",
            })
    except Exception as e:
        return JsonResponse(
            {
                "code": 100,
                "message": str(e),
            }
        )
